import os
import time
import datetime
import subprocess

class PhotoCapture:
    def __init__(self, output_dir="photos", resolution="640x480"):
        """初始化照片拍摄类"""
        self.output_dir = output_dir
        self.resolution = resolution
        self.counter = 0
        self._create_output_dir()
        
    def _create_output_dir(self):
        """创建输出目录"""
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)
            print(f"已创建照片存储目录: {self.output_dir}")
    
    def capture_photo(self):
        """拍摄一张照片"""
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        filename = f"{self.output_dir}/{timestamp}_{self.counter}.jpg"
        
        try:
            # 检查是否安装了fswebcam
            if subprocess.run(["which", "fswebcam"], capture_output=True).returncode != 0:
                print("错误: 未安装fswebcam。请先安装: sudo apt install fswebcam")
                return False
            
            # 使用fswebcam拍摄照片
            command = f"fswebcam --no-banner -r {self.resolution} {filename}"
            result = subprocess.run(command, shell=True, capture_output=True, text=True)
            
            if result.returncode != 0:
                print(f"拍照失败，错误信息: {result.stderr}")
                return False
            
            # 检查文件是否确实创建
            if not os.path.exists(filename):
                print(f"错误: 照片文件未创建: {filename}")
                return False
                
            # 记录到日志文件
            self._log_capture(timestamp)
            self.counter += 1
            print(f"照片拍摄成功: {filename}")
            print(f"文件大小: {os.path.getsize(filename)} 字节")
            return True
            
        except Exception as e:
            print(f"拍照时出错: {str(e)}")
            return False
    
    def _log_capture(self, timestamp):
        """记录拍摄日志"""
        log_file = "photo_log.csv"
        try:
            # 确保日志文件存在并包含标题
            if not os.path.exists(log_file):
                with open(log_file, "w") as f:
                    f.write("timestamp, counter\n")
            
            with open(log_file, "a") as f:
                f.write(f"{timestamp}, {self.counter}\n")
        except IOError as e:
            print(f"无法写入日志文件: {str(e)}")

    def interactive_mode(self):
        """交互式拍摄模式"""
        print("\n=== 照片拍摄系统 ===")
        print("本地时间:", time.asctime(time.localtime()))
        print(f"照片将保存到: {os.path.abspath(self.output_dir)}")
        
        while True:
            try:
                choice = input("\n请输入: 0=拍照, 其他=退出: ").strip()
                if choice == '0':
                    self.capture_photo()
                else:
                    print("退出拍摄模式")
                    break
                    
            except KeyboardInterrupt:
                print("\n用户中断操作")
                break
            except Exception as e:
                print(f"发生错误: {str(e)}")

if __name__ == '__main__':
    # 创建实例并运行交互模式
    camera = PhotoCapture()
    
    # 测试拍摄一张照片
    if camera.capture_photo():
        print("照片拍摄测试成功!")
    else:
        print("照片拍摄测试失败，请检查:")
        print("1. 是否安装了fswebcam (sudo apt install fswebcam)")
        print("2. 是否有摄像头连接")
        print("3. 是否有写入权限")
    
    # 启动交互模式
    camera.interactive_mode()
